<?php
/**
 * Copyright (c) 2018-2019.
 *  This file is part of the moonpie production
 *  (c) johnzhang <875010341@qq.com>
 *  This source file is subject to the MIT license that is bundled
 *  with this source code in the file LICENSE.
 */

namespace moonpie\plugin\wechat_account\model;


use EasyWeChat\Kernel\Support\Arr;
use think\Cache;

class UserTagsModel
{
    protected $account;
    public function __construct(WechatAccount $account)
    {
        $this->account = $account;
    }
    public function getAccount()
    {
        return $this->account;
    }
    public function listTags()
    {
        /** @var \EasyWeChat\OfficialAccount\Application $app */
        $app = $this->getAccount()->getService();
        $cache_key = $this->getCacheKey();
        $tags = Cache::get($cache_key, false);
        if(false === $tags) {
            $response = $app->user_tag->list();
            if(isset($response['tags'])){
                $tags = $response['tags'];
                Cache::set($cache_key, $tags, 86400 * 7);
            }else {
                return false;
            }
        }
        return $tags;
    }
    public function clearCache()
    {
        $cache_key = $this->getCacheKey();
        if(Cache::has($cache_key)) {
            return Cache::rm($cache_key);
        }
        return true;
    }

    protected function getCacheKey()
    {
        $cache_key = 'official_all_user_tags:' . $this->getAccount()->getService()->getId();
        return $cache_key;
    }
    public function createTag($tagName)
    {
        $tag = $this->getAccount()->getService()->user_tag->create($tagName);
        if(Arr::has($tag, 'tag.id')) {
            Cache::rm($this->getCacheKey());
        }
        return $tag;
    }
}